package com.mzj.saas.mservice.lockManager.service;

import com.alibaba.fastjson.JSON;
import com.mzj.saas.commons.DateUtils;
import com.mzj.saas.commons.ResultBean;
import com.mzj.saas.commons.StatusCode;
import com.mzj.saas.commons.enums.LockAuthTypeEnum;
import com.mzj.saas.commons.enums.XzLockOperatorTypeEnum;
import com.mzj.saas.commons.vo.redis.TokenRedisVo;
import com.mzj.saas.mservice.house.repository.LockFrozenRepository;
import com.mzj.saas.mservice.lock.Repository.*;
import com.mzj.saas.mservice.lock.entity.*;
import com.mzj.saas.mservice.lock.service.LockAppService;
import com.mzj.saas.mservice.lockManager.entity.SmartLockBrand;
import com.mzj.saas.mservice.lockManager.entity.SmartLockUser;
import com.mzj.saas.mservice.lockManager.repository.SmartLockBrandRepository;
import com.mzj.saas.mservice.lockManager.repository.SmartLockUserRepository;
import com.mzj.saas.mservice.lockManager.vo.LockUserVO;
import com.mzj.saas.mservice.lockManager.vo.UnbindPersonLockVO;
import com.mzj.saas.mservice.smartlock.service.SmartLockBrandService;
import com.mzj.saas.mservice.smartlock.vo.SmartLockVO;
import com.mzj.saas.mservice.smartlock.vo.yaluete.YltAuthorizationVO;
import com.mzj.saas.mservice.sys.entity.AppUser;
import com.mzj.saas.mservice.sys.entity.User;
import com.mzj.saas.mservice.sys.repository.AppUserRepository;
import com.mzj.saas.mservice.sys.repository.UserRepository;
import com.mzj.saas.redis.RedisService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class LockManagerPersonService {
    private static final Logger log = LoggerFactory.getLogger(LockManagerPersonService.class);

    @Autowired
    private RedisService redisService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private SmartLockRepository smartLockRepository;
    @Autowired
    private SmartLockUserRepository smartLockUserRepository;
    @Autowired
    private SmartLockAuthRepository smartLockAuthRepository;
    @Autowired
    private SmartLockBrandService smartLockBrandService;
    @Autowired
    private SmartLockBrandRepository smartLockBrandRepository;
    @Autowired
    private SmartLockPwdRepository smartLockPwdRepository;
    @Autowired
    private SmartLockCardRepository smartLockCardRepository;
    @Autowired
    private SmartLockFingerprintRepository smartLockFingerprintRepository;
    @Autowired
    private LockFrozenRepository lockFrozenRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private AppUserRepository appUserRepository;
    @Autowired
    private SmartLockBleRepository smartLockBleRepository;
    @Autowired
    private LockAppService lockAppService;
    @Autowired
    @Qualifier("stringRedisTemplate")
    private StringRedisTemplate redisTemplate;

    public ResultBean<List<LockUserVO>> findLockUsers(String accessToken, Long lockId) {
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            String userId = tokenRedisVo.getId();
            Integer loginType = tokenRedisVo.getLoginType();

            String phone = null;
            if (loginType == 1) {
                User user = userRepository.findById(userId);
                phone = user.getMobile();
            } else {
                AppUser appUser = appUserRepository.findByIdOrEnterpriseUserId(userId, userId);
                phone = appUser.getPhone();
            }

            if (lockId == null) {
                return ResultBean.failedResultOfParamWithMsg("智能锁id为空");
            }

            String sql = "SELECT u.id,u.user_id as userId,a.id AS lockAuthId,u.user_type,\n" +
                    "u.user_name AS userName,u.mobile,u.status,u.create_time AS createTime,\n" +
                    "a.pwd_status AS pwdStatus,a.fingerprint_status as fingerprintStatus,a.card_status as cardStatus,\n" +
                    "a.cpu_status AS cpuStatus,a.ble_status AS bleStatus\n" +
                    "FROM `saas_smart_lock_user` u JOIN `saas_smart_lock_auth` a ON u.id = a.lock_user_id  \n" +
                    "WHERE u.lock_id = ? AND u.del_status = 1";
            List<Object> args = new ArrayList<>();
            args.add(lockId);
            List<LockUserVO> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(LockUserVO.class), args.toArray());

            for (LockUserVO vo : list) {
                vo.setCreateTime(DateUtils.format(vo.getCreateTime(), DateUtils.FORMAT_DATETIME_14, DateUtils.FORMAT_DATETIME_14));

                if (userId.equals(vo.getUserId() == null ? "" : vo.getUserId()) || phone.equals(vo.getMobile())) {
                    vo.setFlag(1);
                } else {
                    vo.setFlag(0);
                }
            }

            return ResultBean.successfulResult(list);
        } catch (Exception e) {
            log.error("LockManagerPersonService findLockUsers Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<Object> unbindPersonLock(String accessToken, UnbindPersonLockVO vo) {
        try {
            if (vo == null) {
                return ResultBean.failedResultOfParamWithMsg("参数为空");
            }
            Long lockId = vo.getLockId();

            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }

            Optional<SmartLock> lockOptional = smartLockRepository.findById(lockId);
            if (!lockOptional.isPresent()) {
                return ResultBean.failedResultWithMsg("智能锁不存在");
            }
            SmartLock smartLock = lockOptional.get();

            // 验证验证码
            String phone = redisService.getSmsCodeMobile(vo.getCode());
            if (!StringUtils.isBlank(phone)) {
                if (vo.getPhone().equals(phone)) {
                    List<Map<String, Object>> userlist = jdbcTemplate.queryForList(
                            "select * FROM `saas_smart_lock_user` u where u.lock_id = ? and u.mobile = ? and u.del_status = 1 and u.user_type = 1",
                            lockId, vo.getPhone());
                    if (userlist.isEmpty()) {
                        return ResultBean.failedResultWithMsg("手机号与管理员手机号不符");
                    }

                    // 删除所有个人用户授权
                    List<SmartLockAuth> auths = smartLockAuthRepository.findByLockIdAndBindType(lockId, 1);
                    for (SmartLockAuth smartLockAuth : auths) {
                        Long lockAuthId = smartLockAuth.getId();
                        SmartLockPwd pwd = smartLockPwdRepository.findByLockAuthId(lockAuthId);
                        List<SmartLockCard> cards = smartLockCardRepository.findByLockAuthId(lockAuthId);
                        List<SmartLockFingerprint> fingerprint = smartLockFingerprintRepository.findByLockAuthId(lockAuthId);
                        SmartLockBle ble = smartLockBleRepository.findByLockAuthId(lockAuthId);
                        if (pwd != null || !cards.isEmpty() || !fingerprint.isEmpty() || ble != null) {
                            // 删除密码授权
                            if (pwd != null) {
                                SmartLockVO smartLockVO = new SmartLockVO();
                                smartLockVO.setSn(smartLock.getSn());
                                smartLockVO.setIndex(pwd.getPwdIndex());
                                smartLockVO.setAuthInfoId(lockAuthId);
                                smartLockVO.setIndexNum(pwd.getPwdIndexNum());
                                // 亚略特
                                if (smartLock.getBrandId() == 3L) {
                                    smartLockVO.setfAuthorizationID(pwd.getfAuthorizationId());
                                }
                                // 五代锁嗨小克
                                smartLockVO.setIdentification(pwd.getIdentification());

                                ResultBean<String> stringResultBean = smartLockBrandService.clearPassword(smartLockVO,
                                        smartLock.getBrandId(), "code", lockId);
                                String msg = stringResultBean.getMsg();
                                String code = stringResultBean.getCode();
                                log.info("LockAppService.delAllAuth, del pwd, code={}, msg={}, vo={}", code, msg,
                                        JSON.toJSONString(smartLockVO));

                                smartLockPwdRepository.delete(pwd);
                            }

                            // 删除卡授权
                            if (!cards.isEmpty()) {
                                for (SmartLockCard card : cards) {
                                    SmartLockVO smartLockVO = new SmartLockVO();
                                    smartLockVO.setSn(smartLock.getSn());
                                    smartLockVO.setIndex(card.getCardIndex());
                                    smartLockVO.setAuthInfoId(lockAuthId);
                                    smartLockVO.setCardType(card.getType());
                                    smartLockVO.setIndexNum(card.getCardIndexNum());
                                    // 亚略特
                                    if (smartLock.getBrandId() == 3L) {
                                        smartLockVO.setfAuthorizationID(card.getfAuthorizationId());
                                    }
                                    // 五代锁嗨小克
                                    smartLockVO.setIdentification(card.getIdentification());

                                    ResultBean<String> stringResultBean = smartLockBrandService.clearCard(smartLockVO,
                                            smartLock.getBrandId(), "card");
                                    String msg = stringResultBean.getMsg();
                                    String code = stringResultBean.getCode();
                                    log.info("LockAppService.delAllAuth, del card, code={}, msg={}, vo={}", code, msg,
                                            JSON.toJSONString(smartLockVO));

                                    smartLockCardRepository.delete(card);
                                }
                            }

                            // 删除指纹锁授权
                            if (!fingerprint.isEmpty()) {
                                Optional<SmartLockBrand> optional = smartLockBrandRepository.findById(smartLock.getBrandId());
                                if (optional.isPresent()) {
                                    SmartLockBrand brand = optional.get();
                                    // 品牌支持指纹锁
                                    if (brand.getFingerprintStatus() != null && brand.getFingerprintStatus() == 1) {
                                        for (SmartLockFingerprint fg : fingerprint) {
                                            SmartLockVO smartLockVO = new SmartLockVO();
                                            smartLockVO.setSn(smartLock.getSn());
                                            smartLockVO.setIndex(fg.getFingerprintIndex());
                                            smartLockVO.setIndexNum(fg.getFingerprintIndexNum());
                                            smartLockVO.setAuthInfoId(lockAuthId);
                                            smartLockVO.setIndexNum(fg.getFingerprintIndexNum());
                                            // 亚略特
                                            if (smartLock.getBrandId() == 3L) {
                                                smartLockVO.setfAuthorizationID(fg.getfAuthorizationId());
                                            }

                                            ResultBean<String> stringResultBean = smartLockBrandService
                                                    .clearFingerprint(smartLockVO, smartLock.getBrandId(), "fingerprint");
                                            String msg = stringResultBean.getMsg();
                                            String code = stringResultBean.getCode();
                                            log.info("LockAppService delAllAuth, del fingerprint, code={}, msg={}, vo={}",
                                                    code, msg, JSON.toJSONString(smartLockVO));

                                            smartLockFingerprintRepository.delete(fg);
                                        }
                                    }
                                }
                            }

                            // 删除蓝牙授权
                            if (ble != null) {
                                SmartLockVO smartLockVO = new SmartLockVO();
                                smartLockVO.setSn(smartLock.getSn());
                                smartLockVO.setAuthInfoId(lockAuthId);
                                // 亚略特
                                if (smartLock.getBrandId() == 3L) {
                                    smartLockVO.setfAuthorizationID(ble.getfAuthorizationId());
                                }

                                ResultBean<String> stringResultBean = smartLockBrandService.clearBle(smartLockVO, smartLock.getBrandId());
                                String msg = stringResultBean.getMsg();
                                String code = stringResultBean.getCode();
                                log.info("LockAppService.delAllAuth, del pwd, code={}, msg={}, vo={}", code, msg, JSON.toJSONString(smartLockVO));

                                smartLockBleRepository.delete(ble);
                            }

                        }

                        Optional<SmartLockUser> smartLockUserOptional = smartLockUserRepository.findById(smartLockAuth.getLockUserId());
                        SmartLockUser smartLockUser = smartLockUserOptional.get();
                        smartLockUser.setDelStatus(2);
                        smartLockUserRepository.save(smartLockUser);
                    }

                    smartLockAuthRepository.deleteAll(auths);

                    // 将智能锁修改成单位类型
                    smartLock.setBindType(1);
                    smartLock.setBindStatus(1);

                    // 更新智能锁状态
                    int authCount = smartLockAuthRepository.findSmartLockAuthByLockId(lockId);
                    List<SmartLockAuth> orgAuths = smartLockAuthRepository.findByLockIdAndBindType(lockId, 0);
                    if (orgAuths.size() != 0 && authCount == orgAuths.size()) {
                        smartLock.setMechineStatus(2);
                    } else {
                        smartLock.setMechineStatus(1);
                    }

                    smartLockRepository.save(smartLock);

                    // 更新锁授权人数
                    lockAppService.updateOauthNumber(smartLock.getBrandId(), lockId);
                } else {
                    return ResultBean.failedResultWithMsg("验证码不正确");
                }
            } else {
                return ResultBean.failedResultWithMsg("验证码未找到或已过期");
            }

            return ResultBean.successfulResult(null);
        } catch (Exception e) {
            log.error("LockManagerService unbindPersonLock Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<Object> updateUserStatus(String accessToken, Long lockAuthId, Integer status) {
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            String userId = tokenRedisVo.getId();

            if (lockAuthId == null) {
                return ResultBean.failedResultOfParamWithMsg("授权用户id为空");
            }
            if (status == null) {
                return ResultBean.failedResultOfParamWithMsg("操作类型为空");
            }

            Integer type = null;
            if (status == 1) {
                type = 0;
            } else {
                type = 1;
            }

            // 获取缓存
            Object redis = redisTemplate.opsForValue().get("lock_user_id:" + lockAuthId);
            if (redis != null) {
                return ResultBean.failedResultWithMsg("检测有操作记录，请稍后重试");
            }

            Optional<SmartLockAuth> authOptional = smartLockAuthRepository.findById(lockAuthId);
            if (!authOptional.isPresent()) {
                return ResultBean.failedResultWithMsg("授权用户明细不存在");
            }
            SmartLockAuth smartLockAuth = authOptional.get();

            Optional<SmartLockUser> smartLockUserOpt = smartLockUserRepository.findById(smartLockAuth.getLockUserId());
            if (!smartLockUserOpt.isPresent()) {
                return ResultBean.failedResultWithMsg("个人用户明细不存在");
            }
            SmartLockUser smartLockUser = smartLockUserOpt.get();
            Long lockId = smartLockUser.getLockId();

            Optional<SmartLock> lockOptional = smartLockRepository.findById(lockId);
            if (!lockOptional.isPresent()) {
                return ResultBean.failedResultWithMsg("智能锁不存在");
            }
            SmartLock smartLock = lockOptional.get();

            Date date = new Date();
            SmartLockPwd pwd = smartLockPwdRepository.findByLockAuthId(lockAuthId);
            List<SmartLockCard> cards = smartLockCardRepository.findByLockAuthId(lockAuthId);
            List<SmartLockFingerprint> fingerprint = smartLockFingerprintRepository.findByLockAuthId(lockAuthId);
            SmartLockBle ble = smartLockBleRepository.findByLockAuthId(lockAuthId);
            if (pwd != null || !cards.isEmpty() || !fingerprint.isEmpty() || ble != null) {
                // 新增冻结记录
                String houseId = smartLock.getHouseId();
                String communityName = smartLock.getCommunityName();
                String buildName = smartLock.getBuildName();
                String unitName = smartLock.getUnitName();
                String roomNumber = smartLock.getRoomNumber();

                LockFrozen lockFrozen = new LockFrozen();
                lockFrozen.setType(type);
                lockFrozen.setLockId(lockId);
                lockFrozen.setLockAuditId(lockAuthId);
                lockFrozen.setHouseId(houseId);
                lockFrozen.setMatchUserName(smartLockAuth.getUserName());
                lockFrozen.setCommunityName(communityName);
                lockFrozen.setBuildName(buildName);
                lockFrozen.setUnitName(unitName);
                lockFrozen.setRoomNumber(roomNumber);
                lockFrozen.setOperationId(userId);
                lockFrozen.setOperationTime(date);
                LockFrozen frozenSave = lockFrozenRepository.save(lockFrozen);

                // 冻结密码
                if (pwd != null) {
                    SmartLockVO smartLockVO = new SmartLockVO();
                    smartLockVO.setSn(smartLock.getSn());
                    smartLockVO.setIndex(pwd.getPwdIndex());
                    smartLockVO.setAuthInfoId(lockAuthId);
                    Integer authType = pwd.getAuthType();
                    if (authType == 1 || authType == 2) {
                        smartLockVO.setAuthType(LockAuthTypeEnum.NORMAL_PASS.getValue());
                    } else if (authType == 3) {
                        smartLockVO.setAuthType(LockAuthTypeEnum.TIMES_PASS.getValue());
                        smartLockVO.setTimes(pwd.getTimes());
                    }
                    smartLockVO.setSuspend(type);// 0:解冻 1:冻结
                    smartLockVO.setLockFrozenId(frozenSave.getId());
                    smartLockVO.setIndexNum(pwd.getPwdIndexNum());
                    smartLockVO.setIdentification(pwd.getIdentification());
                    // 亚略特
                    if (smartLock.getBrandId() == 3L) {
                        if (type == 1) {
                            smartLockVO.setfAuthorizationID(pwd.getfAuthorizationId());
                        } else {
                            YltAuthorizationVO yltVO = new YltAuthorizationVO();
                            yltVO.setfLockMAC(smartLock.getMac());
                            yltVO.setfAppUserID(pwd.getfAppUserId());
                            yltVO.setfBeginDate(DateUtils.format(pwd.getStartTime(), DateUtils.FORMAT_DATETIME_14));
                            yltVO.setfEndDate(DateUtils.format(pwd.getEndTime(), DateUtils.FORMAT_DATETIME_14));
                            yltVO.setfOpenByPassword(1);
                            yltVO.setfOpenByIDCard(0);
                            yltVO.setfOpenByBLE(0);
                            yltVO.setfOpenByFinger(0);
                            yltVO.setfOpenByICCard(0);
                            yltVO.setfOpenPassword(pwd.getPassword());
                            smartLockVO.setYltAuth(yltVO);
                        }
                    }

                    ResultBean<String> stringResultBean = smartLockBrandService.freezeOrUnfreeze(smartLockVO,
                            smartLock.getBrandId(), XzLockOperatorTypeEnum.PWD.getValue());
                    String msg = stringResultBean.getMsg();
                    String code = stringResultBean.getCode();
                    if (!code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                        log.error("LockAppService frozenOrUnfrozenAuth---> " + msg);
                        // 失败，删除冻结记录
                        lockFrozenRepository.deleteById(frozenSave.getId());
                    } else {
                        // 冻结后默认待执行
                        pwd.setStatus(0);
                        smartLockPwdRepository.save(pwd);
                        // 亚略特
                        if (smartLock.getBrandId() == 3L) {
                            lockAppService.yltUpdateStatus(pwd, null, null, null, null, type, stringResultBean, smartLockAuth, lockFrozen, smartLock);
                        }
                    }
                }

                // 冻结卡
                if (!cards.isEmpty()) {
                    for (SmartLockCard card : cards) {
                        SmartLockVO smartLockVO = new SmartLockVO();
                        smartLockVO.setSn(smartLock.getSn());
                        smartLockVO.setIndex(card.getCardIndex());
                        smartLockVO.setAuthInfoId(lockAuthId);
                        smartLockVO.setCardType(card.getType());
                        smartLockVO.setSuspend(type);// 0:解冻 1:冻结
                        smartLockVO.setLockFrozenId(frozenSave.getId());
                        smartLockVO.setIndexNum(card.getCardIndexNum());
                        smartLockVO.setIdentification(card.getIdentification());
                        // 亚略特
                        if (smartLock.getBrandId() == 3L) {
                            if (type == 1) {
                                smartLockVO.setfAuthorizationID(card.getfAuthorizationId());
                            } else {
                                YltAuthorizationVO yltVO = new YltAuthorizationVO();
                                yltVO.setfLockMAC(smartLock.getMac());
                                yltVO.setfAppUserID(card.getfAppUserId());
                                yltVO.setfBeginDate(DateUtils.format(card.getStartTime(), DateUtils.FORMAT_DATETIME_14));
                                yltVO.setfEndDate(DateUtils.format(card.getEndTime(), DateUtils.FORMAT_DATETIME_14));
                                yltVO.setfOpenByPassword(0);
                                yltVO.setfOpenByBLE(0);
                                yltVO.setfOpenByFinger(0);
                                if (card.getType() == 1) {
                                    yltVO.setfOpenByIDCard(1);
                                    yltVO.setfOpenByICCard(0);
                                } else {
                                    yltVO.setfOpenByIDCard(0);
                                    yltVO.setfOpenByICCard(1);
                                }
                                yltVO.setfIDCardID(card.getCardId());
                                yltVO.setfIDCardNumber(card.getCardNumber());
                                smartLockVO.setYltAuth(yltVO);
                            }
                        }

                        ResultBean<String> stringResultBean = smartLockBrandService.freezeOrUnfreezeCard(smartLockVO,
                                smartLock.getBrandId(), XzLockOperatorTypeEnum.CARD.getValue());
                        String msg = stringResultBean.getMsg();
                        String code = stringResultBean.getCode();
                        if (!code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                            log.error("LockAppService frozenOrUnfrozenAuth---> " + msg);
                            // 失败，删除冻结记录
                            lockFrozenRepository.deleteById(frozenSave.getId());
                        } else {
                            // 冻结后默认待执行
                            card.setStatus(0);
                            smartLockCardRepository.save(card);
                            // 亚略特
                            if (smartLock.getBrandId() == 3L) {
                                lockAppService.yltUpdateStatus(null, card, null, null, null, type, stringResultBean, smartLockAuth, lockFrozen, smartLock);
                            }
                        }
                    }
                }

                // 指纹锁
                if (!fingerprint.isEmpty()) {
                    Optional<SmartLockBrand> optional = smartLockBrandRepository.findById(smartLock.getBrandId());
                    if (optional.isPresent()) {
                        SmartLockBrand brand = optional.get();
                        // 品牌支持指纹锁
                        if (brand.getFingerprintStatus() != null && brand.getFingerprintStatus() == 1) {
                            for (SmartLockFingerprint fg : fingerprint) {
                                SmartLockVO smartLockVO = new SmartLockVO();
                                smartLockVO.setSn(smartLock.getSn());
                                smartLockVO.setIndex(fg.getFingerprintIndex());
                                smartLockVO.setIndexNum(fg.getFingerprintIndexNum());
                                smartLockVO.setAuthInfoId(lockAuthId);
                                smartLockVO.setSuspend(type);// 0:解冻 1:冻结
                                smartLockVO.setLockFrozenId(frozenSave.getId());
                                smartLockVO.setIndexNum(fg.getFingerprintIndexNum());
                                // 亚略特
                                if (smartLock.getBrandId() == 3L) {
                                    if (type == 1) {
                                        smartLockVO.setfAuthorizationID(fg.getfAuthorizationId());
                                    } else {
                                        YltAuthorizationVO yltVO = new YltAuthorizationVO();
                                        yltVO.setfLockMAC(smartLock.getMac());
                                        yltVO.setfAppUserID(fg.getfAppUserId());
                                        yltVO.setfBeginDate(DateUtils.format(fg.getStartTime(), DateUtils.FORMAT_DATETIME_14));
                                        yltVO.setfEndDate(DateUtils.format(fg.getEndTime(), DateUtils.FORMAT_DATETIME_14));
                                        yltVO.setfOpenByPassword(0);
                                        yltVO.setfOpenByIDCard(0);
                                        yltVO.setfOpenByBLE(0);
                                        yltVO.setfOpenByFinger(1);
                                        yltVO.setfOpenByICCard(0);
                                        yltVO.setfFingerFeature(fg.getFingerprint());
                                        smartLockVO.setYltAuth(yltVO);
                                    }
                                }

                                ResultBean<String> stringResultBean = smartLockBrandService.freezeOrUnfreezeFingerprint(
                                        smartLockVO, smartLock.getBrandId(), XzLockOperatorTypeEnum.FINGERPRINT.getValue());
                                String msg = stringResultBean.getMsg();
                                String code = stringResultBean.getCode();
                                if (code != StatusCode.SUCCESS_CODE_10000.getErrorCode()) {
                                    log.error("LockAppService deleteUser---> " + msg);
                                    // 失败，删除冻结记录
                                    lockFrozenRepository.deleteById(frozenSave.getId());
                                } else {
                                    // 冻结后默认待执行
                                    fg.setStatus(0);
                                    smartLockFingerprintRepository.save(fg);
                                    // 亚略特
                                    if (smartLock.getBrandId() == 3L) {
                                        lockAppService.yltUpdateStatus(null, null, fg, null, null, type, stringResultBean, smartLockAuth, lockFrozen, smartLock);
                                    }
                                }
                            }
                        }
                    }
                }

                // 蓝牙
                if (ble != null) {
                    SmartLockVO smartLockVO = new SmartLockVO();
                    smartLockVO.setIdentification(ble.getIdentification());
                    smartLockVO.setSn(smartLock.getSn());
                    smartLockVO.setAuthInfoId(lockAuthId);
                    smartLockVO.setSuspend(type);// 0:解冻 1:冻结
                    smartLockVO.setLockFrozenId(frozenSave.getId());
                    // 亚略特
                    if (smartLock.getBrandId() == 3L) {
                        if (type == 1) {
                            smartLockVO.setfAuthorizationID(ble.getfAuthorizationId());
                        } else {
                            YltAuthorizationVO yltVO = new YltAuthorizationVO();
                            yltVO.setfLockMAC(smartLock.getMac());
                            yltVO.setfAppUserID(ble.getfAppUserId());
                            yltVO.setfBeginDate(DateUtils.format(ble.getStartTime(), DateUtils.FORMAT_DATETIME_14));
                            yltVO.setfEndDate(DateUtils.format(ble.getEndTime(), DateUtils.FORMAT_DATETIME_14));
                            yltVO.setfOpenByPassword(0);
                            yltVO.setfOpenByIDCard(0);
                            yltVO.setfOpenByBLE(1);
                            yltVO.setfOpenByFinger(0);
                            yltVO.setfOpenByICCard(0);
                            smartLockVO.setYltAuth(yltVO);
                        }
                    }

                    ResultBean<String> stringResultBean = smartLockBrandService.freezeOrUnfreezeBle(smartLockVO, smartLock.getBrandId());
                    String msg = stringResultBean.getMsg();
                    String code = stringResultBean.getCode();
                    if (!code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                        log.error("LockAppService frozenOrUnfrozenAuth---> " + msg);
                        // 失败，删除冻结记录
                        lockFrozenRepository.deleteById(frozenSave.getId());
                        return ResultBean.failedResultWithCodeAndMsg(code, msg);
                    } else {
                        // 冻结后默认待执行
                        ble.setStatus(0);
                        smartLockBleRepository.save(ble);
                        // 亚略特
                        if (smartLock.getBrandId() == 3L) {
                            lockAppService.yltUpdateStatus(null, null, null, ble, null, type, stringResultBean, smartLockAuth, lockFrozen, smartLock);
                        }
                    }
                }

            }

            // 修改业务状态
            smartLockUser.setStatus(status);
            smartLockUserRepository.save(smartLockUser);

            // 更新亚略特智能锁状态
            lockAppService.yltUpdateLockStatus(smartLock, type);

            // 更新锁授权人数
            lockAppService.updateOauthNumber(smartLock.getBrandId(), lockId);

            // 操作成功设置缓存，防止重复操作
            redisTemplate.opsForValue().set("lock_user_id:" + lockAuthId, "", 1, TimeUnit.MINUTES);

            return ResultBean.successfulResult(null);
        } catch (Exception e) {
            log.error("LockManagerPersonService updateUserStatus Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<Object> deleteUser(String accessToken, Long lockAuthId) {
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }

            if (lockAuthId == null) {
                return ResultBean.failedResultOfParamWithMsg("授权用户id为空");
            }

            Optional<SmartLockAuth> authOptional = smartLockAuthRepository.findById(lockAuthId);
            if (!authOptional.isPresent()) {
                return ResultBean.failedResultWithMsg("授权用户明细不存在");
            }
            SmartLockAuth auth = authOptional.get();

            Optional<SmartLockUser> smartLockUserOpt = smartLockUserRepository.findById(auth.getLockUserId());
            if (!smartLockUserOpt.isPresent()) {
                return ResultBean.failedResultWithMsg("个人用户明细不存在");
            }
            SmartLockUser smartLockUser = smartLockUserOpt.get();
            Long lockId = smartLockUser.getLockId();

            Optional<SmartLock> lockOptional = smartLockRepository.findById(lockId);
            if (!lockOptional.isPresent()) {
                return ResultBean.failedResultWithMsg("智能锁不存在");
            }
            SmartLock smartLock = lockOptional.get();

            SmartLockPwd pwd = smartLockPwdRepository.findByLockAuthId(lockAuthId);
            List<SmartLockCard> cards = smartLockCardRepository.findByLockAuthId(lockAuthId);
            List<SmartLockFingerprint> fingerprint = smartLockFingerprintRepository.findByLockAuthId(lockAuthId);
            SmartLockBle ble = smartLockBleRepository.findByLockAuthId(lockAuthId);

            // 删除密码授权
            if (pwd != null) {
                SmartLockVO smartLockVO = new SmartLockVO();
                smartLockVO.setSn(smartLock.getSn());
                smartLockVO.setIndex(pwd.getPwdIndex());
                smartLockVO.setAuthInfoId(lockAuthId);
                smartLockVO.setIndexNum(pwd.getPwdIndexNum());
                // 亚略特
                if (smartLock.getBrandId() == 3L) {
                    smartLockVO.setfAuthorizationID(pwd.getfAuthorizationId());
                }
                smartLockVO.setIdentification(pwd.getIdentification());

                ResultBean<String> stringResultBean = smartLockBrandService.clearPassword(smartLockVO,
                        smartLock.getBrandId(), "code", lockAuthId);
                String msg = stringResultBean.getMsg();
                String code = stringResultBean.getCode();
                log.info("LockAppService.delAllAuth, del pwd, code={}, msg={}, vo={}", code, msg,
                        JSON.toJSONString(smartLockVO));

                smartLockPwdRepository.delete(pwd);
            }

            // 删除卡授权
            if (!cards.isEmpty()) {
                for (SmartLockCard card : cards) {
                    SmartLockVO smartLockVO = new SmartLockVO();
                    smartLockVO.setSn(smartLock.getSn());
                    smartLockVO.setIndex(card.getCardIndex());
                    smartLockVO.setAuthInfoId(lockAuthId);
                    smartLockVO.setCardType(card.getType());
                    smartLockVO.setIndexNum(card.getCardIndexNum());
                    // 亚略特
                    if (smartLock.getBrandId() == 3L) {
                        smartLockVO.setfAuthorizationID(pwd.getfAuthorizationId());
                    }
                    smartLockVO.setIdentification(card.getIdentification());

                    ResultBean<String> stringResultBean = smartLockBrandService.clearCard(smartLockVO,
                            smartLock.getBrandId(), "card");
                    String msg = stringResultBean.getMsg();
                    String code = stringResultBean.getCode();
                    log.info("LockAppService.delAllAuth, del card, code={}, msg={}, vo={}", code, msg,
                            JSON.toJSONString(smartLockVO));

                    smartLockCardRepository.delete(card);
                }
            }

            // 删除指纹锁授权
            if (!fingerprint.isEmpty()) {
                Optional<SmartLockBrand> optional = smartLockBrandRepository.findById(smartLock.getBrandId());
                if (optional.isPresent()) {
                    SmartLockBrand brand = optional.get();
                    // 品牌支持指纹锁
                    if (brand.getFingerprintStatus() != null && brand.getFingerprintStatus() == 1) {
                        for (SmartLockFingerprint fg : fingerprint) {
                            SmartLockVO smartLockVO = new SmartLockVO();
                            smartLockVO.setSn(smartLock.getSn());
                            smartLockVO.setIndex(fg.getFingerprintIndex());
                            smartLockVO.setIndexNum(fg.getFingerprintIndexNum());
                            smartLockVO.setAuthInfoId(lockAuthId);
                            smartLockVO.setIndexNum(fg.getFingerprintIndexNum());
                            // 亚略特
                            if (smartLock.getBrandId() == 3L) {
                                smartLockVO.setfAuthorizationID(pwd.getfAuthorizationId());
                            }

                            ResultBean<String> stringResultBean = smartLockBrandService
                                    .clearFingerprint(smartLockVO, smartLock.getBrandId(), "fingerprint");
                            String msg = stringResultBean.getMsg();
                            String code = stringResultBean.getCode();
                            log.info("LockAppService delAllAuth, del fingerprint, code={}, msg={}, vo={}",
                                    code, msg, JSON.toJSONString(smartLockVO));

                            smartLockFingerprintRepository.delete(fg);
                        }
                    }
                }
            }

            // 删除蓝牙授权
            if (ble != null) {
                SmartLockVO smartLockVO = new SmartLockVO();
                smartLockVO.setSn(smartLock.getSn());
                smartLockVO.setAuthInfoId(lockAuthId);
                // 亚略特
                if (smartLock.getBrandId() == 3L) {
                    smartLockVO.setfAuthorizationID(ble.getfAuthorizationId());
                }

                ResultBean<String> stringResultBean = smartLockBrandService.clearBle(smartLockVO, smartLock.getBrandId());
                String msg = stringResultBean.getMsg();
                String code = stringResultBean.getCode();
                log.info("LockAppService.delAllAuth, del pwd, code={}, msg={}, vo={}", code, msg, JSON.toJSONString(smartLockVO));

                smartLockBleRepository.delete(ble);
            }

            // 修改删除状态
            smartLockUser.setDelStatus(2);
            smartLockUserRepository.save(smartLockUser);
            smartLockAuthRepository.deleteById(lockAuthId);

            // 更新锁授权人数
            lockAppService.updateOauthNumber(smartLock.getBrandId(), lockId);

            return ResultBean.successfulResult(null);
        } catch (Exception e) {
            log.error("LockManagerPersonService deleteUser Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<Object> addUser(String accessToken, Long lockId, String userName, String phone) {
        try {
            if (lockId == null) {
                return ResultBean.failedResultOfParamWithMsg("智能锁id为空");
            }
            if (StringUtils.isBlank(userName)) {
                return ResultBean.failedResultOfParamWithMsg("用户名为空");
            }
            if (StringUtils.isBlank(phone)) {
                return ResultBean.failedResultOfParamWithMsg("手机号码为空");
            }

            Optional<SmartLock> smartLockOpt = smartLockRepository.findById(lockId);
            if (!smartLockOpt.isPresent()) {
                return ResultBean.failedResultWithMsg("智能锁不存在");
            }
            SmartLock smartLock = smartLockOpt.get();

            Date date = new Date();
            SmartLockUser smartLockUser = new SmartLockUser();
            smartLockUser.setLockId(lockId);
            smartLockUser.setHouseId(smartLock.getHouseId());
            smartLockUser.setMatchUserId(smartLock.getMatchUserId());
            AppUser appUser = appUserRepository.findByPhone(phone);
            if (appUser != null) {
                smartLockUser.setUserId(appUser.getId());
            }
            smartLockUser.setUserName(userName);
            smartLockUser.setMobile(phone);
            smartLockUser.setStatus(1);
            smartLockUser.setDelStatus(1);
            smartLockUser.setCreateTime(date);
            smartLockUser.setUserType(2);// 添加用户
            SmartLockUser save = smartLockUserRepository.save(smartLockUser);

            // 生成授权明细数据
            SmartLockAuth smartLockAuth = new SmartLockAuth();
            smartLockAuth.setLockId(lockId);
            smartLockAuth.setHouseId(smartLock.getHouseId());
            smartLockAuth.setBindType(1);
            smartLockAuth.setMatchUserId(smartLock.getMatchUserId());
            smartLockAuth.setAuthorUserId(save.getUserId());
            smartLockAuth.setUserName(save.getUserName());
            smartLockAuth.setMobile(save.getMobile());
            smartLockAuth.setPwdStatus(0);
            smartLockAuth.setFingerprintStatus(0);
            smartLockAuth.setCardStatus(0);
            smartLockAuth.setCpuStatus(0);
            smartLockAuth.setBleStatus(0);
            smartLockAuth.setCreateTime(date);
            smartLockAuth.setUserType(2);
            smartLockAuth.setLockUserId(save.getId());
            smartLockAuthRepository.save(smartLockAuth);

            return ResultBean.successfulResult(null);
        } catch (Exception e) {
            log.error("LockManagerPersonService addUser Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }


}
